package com.csust.automaticteach.utils;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassNameFileReadUtil
 * @Description 特殊格式文件的读取（例如.doc/.docx/.pdf）
 * @Author钰玟
 * @Date2025/6/22 下午7:54
 * @Version 1.0
 **/
@Component
public class FileReaderUtil {
    public List<String> readFile(InputStream inputStream, String fileType) throws IOException {
        switch (fileType) {
            case "doc":
                return readDocFile(inputStream);
            case "docx":
                return readDocxFile(inputStream);
            case "pdf":
                return readPdfFile(inputStream);
            default:
                throw new IllegalArgumentException("不支持的文件类型");
        }
    }

    private List<String> readDocFile(InputStream inputStream) throws IOException {
        List<String> paragraphs = new ArrayList<>();
        try (HWPFDocument document = new HWPFDocument(inputStream);
             WordExtractor extractor = new WordExtractor(document)) {
            String[] paragraphTexts = extractor.getParagraphText();
            for (String paragraph : paragraphTexts) {
                paragraphs.add(paragraph);
            }
        }
        return paragraphs;
    }

    private List<String> readDocxFile(InputStream inputStream) throws IOException {
        List<String> paragraphs = new ArrayList<>();
        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                paragraphs.add(paragraph.getText());
            }
        }
        return paragraphs;
    }

    private List<String> readPdfFile(InputStream inputStream) throws IOException {
        List<String> paragraphs = new ArrayList<>();
        byte[] pdfBytes = inputStream.readAllBytes(); // 将 InputStream 转换为字节数组
        try (PDDocument document = Loader.loadPDF(pdfBytes)) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            String text = pdfStripper.getText(document);
            for (String paragraph : text.split("\n")) {
                paragraphs.add(paragraph);
            }
        }
        return paragraphs;
    }
}
